package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"gitignore/gitignorerpc/gitignorerpc"
	"gitignore/gitignorerpc/internal/svc"
	"gitignore/models/cache"
	"gitignore/models/mysql"
	"math/rand"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *gitignorerpc.LoginRequest) (*gitignorerpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var findUser mysql.User

	err := findUser.FindUserByPhoneNum(mysql.DB, in.PhoneNum)
	if err != nil {
		return nil, errors.New("手机号不存在，请立即注册")
	}

	if findUser.Phone_num != in.PhoneNum {
		return nil, errors.New("请输入正确的手机号")
	}
	user := mysql.User{
		//Model: gorm.Model{},
		//Model:       gorm.Model{},
		Phone_num:   in.PhoneNum,
		Password:    in.Password,
		Avatar_link: "http://t4kat4rvf.hn-bkt.clouddn.com/A445F06B110BC9DB2B56A03A8CEE4ECF.png",
		Nick_name:   fmt.Sprintf("用户_%s", rand.Intn(1000)),
	}

	err = user.FindUserByLogin(mysql.DB, in.PhoneNum)
	if err != nil {
		return nil, errors.New("登入失败")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.PhoneNum).Result()
	if result == in.PhoneNum {
		return nil, errors.New("验证码错误")
	}

	return &gitignorerpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
